home *** CD-ROM | disk | FTP | other *** search
/ Apple Developer Connection Student Program / ADC Tools Sampler CD Disk 3 1999.iso / Documentation / Books / Learn Java on the Macintosh / Learn Java Projects / 14.02 - next prime / NextPrime.java next >
Text File  |  1996-04-22  |  2KB  |  58 lines

  1. /* -------------------------------------------------------------
  2. This stand-alone application finds the next prime after the
  3. integer passed to it as a command line parameter.
  4.  
  5. Java's classes: Applet    (applet)
  6.                 Exception (lang)
  7.                 String    (lang)
  8.                 Integer   (lang)
  9.                 Math      (lang)     to find the square root
  10.  
  11. Custom classes: NextPrime
  12.  
  13. ------------------------------------------------------------- */
  14.  
  15. public class NextPrime {
  16.     public static void main(String[] args) {
  17.    
  18.         int     startingPoint, candidate, last, i;
  19.         boolean isPrime;
  20.  
  21.         if (args.length == 1) {
  22.            try {
  23.               Integer integer = new Integer(args[0]);
  24.               startingPoint = integer.intValue();
  25.            } catch (Exception e) {
  26.               return;
  27.            }
  28.         } else
  29.             return;
  30.  
  31.         if ( startingPoint < 2 ) {
  32.                candidate = 2;
  33.         } else if ( startingPoint == 2 ) {
  34.             candidate = 3;
  35.         } else {
  36.         
  37.                candidate = startingPoint;
  38.             if (candidate % 2 == 0)                  /* Test only odd numbers */
  39.                 candidate--;
  40.             do {
  41.             
  42.                 isPrime = true;                      /* Assume glorious success */
  43.                 candidate += 2;                      /* Bump to the next number to test */
  44.                 last = (int)Math.sqrt( candidate );  /* We'll check to see if candidate */
  45.                                                      /* has any factors, from 2 to last */
  46.                                                      
  47.                    /* Loop through odd numbers only */
  48.                 for ( i = 3; (i <= last) && isPrime; i += 2 ) {
  49.                        if ( (candidate % i) == 0 )
  50.                         isPrime = false;
  51.                    }
  52.             } while ( ! isPrime );
  53.            }
  54.  
  55.         System.out.println( "The next prime after " + startingPoint + " is " + candidate);
  56.         
  57.     }
  58. }